import os
from pathlib import Path


# 获取环境变量配置
def get_database_uri():
    # 数据库类型，支持 sqlite, mysql, postgresql 等
    db_type = os.environ.get("DB_TYPE", "sqlite")
    
    # SQLite 配置
    sqlite_db_path = os.environ.get("SQLITE_DB_PATH", "db.sqlite3")
    
    # 其他数据库配置
    db_host = os.environ.get("DB_HOST", "localhost")
    db_port = os.environ.get("DB_PORT", "")
    db_name = os.environ.get("DB_NAME", "resicloud")
    db_user = os.environ.get("DB_USER", "")
    db_password = os.environ.get("DB_PASSWORD", "")
    
    # 确保instance目录存在
    instance_dir = Path(__file__).parent.parent / "instance"
    instance_dir.mkdir(exist_ok=True)
    
    # 根据数据库类型构建连接URI
    if db_type == "sqlite":
        db_path = instance_dir / sqlite_db_path
        return f"sqlite:///{db_path}"
    elif db_type == "mysql":
        port_str = f":{db_port}" if db_port else ""
        return f"mysql+pymysql://{db_user}:{db_password}@{db_host}{port_str}/{db_name}"
    elif db_type == "postgresql":
        port_str = f":{db_port}" if db_port else ""
        return f"postgresql://{db_user}:{db_password}@{db_host}{port_str}/{db_name}"
    else:
        # 默认使用SQLite
        return "sqlite:///db.sqlite3"


class Config:
    # 基本配置
    SECRET_KEY = os.environ.get("SECRET_KEY", "dev_secret")
    JWT_SECRET_KEY = os.environ.get("JWT_SECRET_KEY", "jwt_secret")
    
    # 数据库URI配置
    SQLALCHEMY_DATABASE_URI = get_database_uri()
    
    # 其他SQLAlchemy配置
    SQLALCHEMY_TRACK_MODIFICATIONS = False
